package com.wjb.listener;

/**
 * @author : 王济彬
 * @date: 2025/5/25 - 05 - 25 - 17:01
 * @Description: com.wjb.listener
 * @version: 1.0
 */

import com.rabbitmq.client.Channel;
import com.wjb.config.ExchangeConfig;
import com.wjb.controller.OrderCreateController;
import com.wjb.pojo.dto.OrderxDto;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Date;

@Configuration
public class OrderQueueListener {

    @Autowired
    private OrderCreateController orderCreateController;
    private static int count = 1;

    private static final String CREATE = "create order";
    @RabbitListener(queues = ExchangeConfig.ORDER_QUEUE)
    public void consumer(String message, Channel channel, Message msg){   //channel需要在配置类中进行转换ack为手动模式，msg则包含消息队列所有信息如前面的message以及对应设置在生产者中MessagePostProcessor（）方法下的数据
        System.out.println("消息队列接收到的消息为" + message);
        if(CREATE.equals(message)){
            String correlationId = msg.getMessageProperties().getCorrelationId();
            System.out.println("消息的CorrelationId为" + correlationId);
            //模拟创建订单
            OrderxDto orderDto = new OrderxDto();
            orderDto.setOrderName("msb");
            orderDto.setOrderCreateName("wjb");
            orderDto.setOrderCreateTime(new Date());
            orderDto.setProductId(1);
            System.out.println("创建订单成功");
            orderCreateController.createOrder(orderDto);
            System.out.println("创建订单成功2");
            try {
                channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else{
            try {
                channel.basicReject(msg.getMessageProperties().getDeliveryTag(), true);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
